package com.base.controller;

import com.base.po.voip.*;
import com.base.service.*;
import com.base.utils.Page;
import com.base.utils.Produce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 淘客订单
 *
 * @author K
 *
 */
@Controller
@RequestMapping("/admin")
public class index_RebateOrder {
    @Autowired
    private RebateOrdersService rebateOrdersService;
    @Autowired
    private SubscribersService subscribersService;
    @Autowired
    private ShopOrderService shopOrderService;
    @Autowired
    private RebateDisService rebateDisService;
    @Autowired
    private UsersService usersService;

    // 自营商城订单首页
    @RequestMapping("/rebateOrders")
    public ModelAndView index(HttpServletRequest request) throws Exception {
        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        Page page = new Page();
        Users users = usersService.selectByPrimaryKey(adminUserId);

        List<RebateOrders> rebateOrders = null;
        page.setCurrentPageNo(1);
//        if(users.getRole() == 0) {
//            page.setRecordTotal(rebateOrdersService.countAll(null,null,null));
        page.setRecordTotal(5000);
        rebateOrders = rebateOrdersService.selectAll(page, null,null, null, null);
//        }
//        if(users.getRole() == 1) {
//            page.setRecordTotal(rebateOrdersService.countAll(adminUserId,null,null));
//            page.setRecordTotal(5000);
//            rebateOrders = rebateOrdersService.selectAll(page, adminUserId,null,null);
//        }

        for (RebateOrders r : rebateOrders){
            Subscribers subscribers = subscribersService.selectByRebatePid(adminUserId, r.getRelationId());
            r.setMobile(subscribers == null ? null : subscribers.getMobile());
        }

        request.setAttribute("rebateOrders", rebateOrders);
        request.setAttribute("totlenum", page.getRecordTotal());// 传入session中
        request.setAttribute("curPage", page.getCurrentPageNo());// 传入session中
        request.setAttribute("status", 0);
        // 设置页面进行跳转
        modelAndView.setViewName("jsp/index_RebateOrder");
        return modelAndView;
    }

    @RequestMapping("/selectRebateOrder")
    public ModelAndView selectRebateOrder(HttpServletRequest request, Integer curPage, String mobile,
                                            String tradeId, Byte status, String date) {
        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");

        ModelAndView modelAndView = new ModelAndView();
        Page page = new Page();
        Users users = usersService.selectByPrimaryKey(adminUserId);

        List<RebateOrders> rebateOrders = null;
        Integer choose = 2;
        if(tradeId != null && !tradeId.equals("") || status != 0) {
            choose = 1;
        }

        String fTradeId = null;
        String fMobile = null;
        Byte fStatus = null;

        if(tradeId != null && !tradeId.equals("")) {
            fTradeId = tradeId;
        }
        if(mobile != null && !mobile.equals("")) {
            fMobile = mobile;
        }
        if(status != 0) {
            fStatus = status;
        }

        page.setCurrentPageNo(curPage);
//        if(users.getRole() == 0) {
//            page.setRecordTotal(rebateOrdersService.countAll(null,null,null));
            page.setRecordTotal(5000);
            rebateOrders = rebateOrdersService.selectAll(page, null,null, null, null);
//        }
//        if(users.getRole() == 1) {
//            page.setRecordTotal(rebateOrdersService.countAll(adminUserId, fStatus, fMobile));
//            page.setRecordTotal(5000);
//            rebateOrders = rebateOrdersService.selectAll(page, adminUserId, fStatus,  fMobile);
//        }

        if (choose == 2){
//            if(users.getRole() == 0) {
//                page.setRecordTotal(rebateOrdersService.countAll(null,null,null));
                page.setRecordTotal(5000);
                rebateOrders = rebateOrdersService.selectAll(page, null,null, null, null);
//            }
//            if(users.getRole() == 1) {
//                page.setRecordTotal(rebateOrdersService.countAll(adminUserId,null,null));
//                page.setRecordTotal(5000);
//                rebateOrders = rebateOrdersService.selectAll(page, adminUserId,null,null);
//            }
        }

        if(tradeId != null && !tradeId.equals("") && date != null && !date.equals("")) {
            // 未查询到订单 接口查询订单
            Users pUsers = null;
            if (users.getRole() == 1){
                pUsers = users;
            }
            if (users.getRole() == 2){
                pUsers = usersService.selectByPrimaryKey(users.getParentid());
            }

            String yDay = Produce.addDateMinut(date, -1);
            String eDay = Produce.addDateMinut(date, 1);
            rebateOrders = myqOrder(pUsers, yDay, 1, eDay, page, fTradeId, fStatus);
        }

        for (RebateOrders r : rebateOrders){
            Subscribers subscribers = subscribersService.selectByPid(adminUserId, r.getpId());
            if (subscribers == null && r.getUserid() != null){
                subscribers = subscribersService.selectByPrimaryKey(r.getUserid());
            }
            r.setMobile(subscribers == null ? null : subscribers.getMobile());
        }

        request.setAttribute("rebateOrders", rebateOrders);
        request.setAttribute("totlenum", page.getRecordTotal());// 传入session中
        request.setAttribute("curPage", page.getCurrentPageNo());// 传入session中
        request.setAttribute("mobile", mobile);
        request.setAttribute("tradeId", tradeId);
        request.setAttribute("status", status);

        modelAndView.setViewName("jsp/index_RebateOrder");
        return modelAndView;
    }

    private List<RebateOrders> myqOrder(Users users, String yDay, int size, String eDay, Page pages, String fTradeId, Byte fStatus) {
//        System.out.println("开始查询订单");
//        if (users != null && users.getDatastatus() == true) {
//            int v1num = 0; // 接口调用次数
//            BigDecimal ratio = new BigDecimal(1); // 一级分润 默认0
//            BigDecimal sper = new BigDecimal(1); // 二级分润 默认1
//            for (int i = 0; i < size; i++) {
//                String sTime = null;
//                String eTime = null;
//                try {
//                    sTime = URLEncoder.encode(yDay, "GBK"); // 获取时间进行URLEncoder编码
//                    eTime = URLEncoder.encode(eDay, "GBK"); // 获取时间进行URLEncoder编码
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                // 获取订单信息
//                int page = 1; // 第一页
//                boolean status; // 判断是否继续获取下一页数据
//                String url = "https://api.open.21ds.cn/apiv2/tbkorderdetailsget"; // 喵有券URL
//                String param = "apkey=" + users.getMyqappkey() + "&start_time=" + sTime + "&end_time=" + eTime +"&tbname=" + users.getTbname() + "&page_size=100&page_no=1&order_scene=2";
//                try {
//                    if (v1num >= 950) {
//                        // 线程睡眠
//                        try {
//                            Thread.sleep(60000); // 接口调用次数已经为950次 下一分钟继续
//                        } catch (InterruptedException e) {
//                            System.out.println("查询过于频繁");
//                        }
//                        v1num = 0;
//                    }
//                    v1num++; // +1
//                    String order = WebHelper.GetData(url, param);
//                    System.out.println(order);
////                        Map<String, Object> map = new HashMap<>();
////                        map.put("data", Tbk_Data.class);
////                        Tbk_Order analyzeOrder = (Tbk_Order)JSONObject.toBean(JSONObject.fromObject(order), Tbk_Order.class, map); // 解析订单数据
//                    Tbk_Order analyzeOrder = JSON.toJavaObject(JSON.parseObject(order), Tbk_Order.class);
//                    // 查询到订单信息
//                    if (analyzeOrder != null && analyzeOrder.getCode() == 200) {
//                        status = true;
//                        page++;
//                        // 解析订单
//                        List<Tbk_Data> n_tbk_order = analyzeOrder.getData();
//                        for (int j = 0; j < n_tbk_order.size(); j++) {
//                            Tbk_Data nto = n_tbk_order.get(j); // 获取到的订单信息
//                            RebateOrders ro = new RebateOrders(); // 数据库订单信息
//                            // 参数进行赋值
//                            ro.setpId("mm_" + users.getTbonepid() + "_" + nto.getSite_id() + "_" + nto.getAdzone_id()); // PID
//                            ro.setAuctionCategory(nto.getItem_category_name()); // 类目名称
//                            ro.setCommission(new BigDecimal(nto.getPub_share_fee())); // 预估收入 推广者获得的收入金额，对应联盟后台报表“预估收入”，未确认收货时显示为0
//                            ro.setCommissionRate(new BigDecimal(nto.getPub_share_rate())); // 推广者获得的分成比率，对应联盟后台报表“分成比率”
//                            ro.setCreateTime(nto.getTk_create_time()); // 淘客订单创建时间
//                            ro.setEarningTime(nto.getTk_earning_time()); // 淘客订单结算时间
//                            ro.setIncomeRate(new BigDecimal(nto.getIncome_rate())); // 收入比率 卖家设置佣金比率+平台补贴比率
//                            ro.setItemNum(Integer.parseInt(nto.getItem_num())); // 商品数量
//                            ro.setItemTitle(nto.getItem_title()); // 商品标题
//                            ro.setNumIid(nto.getItem_id()); // 商品ID
//                            ro.setPictUrl(nto.getItem_img()); // 商品主图
//                            ro.setOrderType(nto.getOrder_type()); // 订单类型 天猫:1，聚划算:2，航旅:3，阿里云:4
//                            ro.setPayPrice(nto.getPay_price() == null ? new BigDecimal(0) : nto.getPay_price()); // 	实际支付金额 订单结算后会显示对应支付金额，不结算显示为0
//                            ro.setPrice(new BigDecimal(nto.getItem_price())); // 单价
//                            ro.setPubSharePreFee(new BigDecimal(nto.getPub_share_pre_fee())); // 效果预估
//                            ro.setTkStatus((byte) (nto.getTk_status() == null || nto.getTk_status().isEmpty() ? 0 : Integer.parseInt(nto.getTk_status()))); // 淘客订单状态
//                            ro.setTradeId(nto.getTrade_id()); // 订单ID
//                            ro.setAlipayTotalPrice(ro.getTkStatus() == 3 ? ro.getPayPrice() : nto.getAlipay_total_price() == null ? new BigDecimal(0) : new BigDecimal(nto.getAlipay_total_price())); // 付款金额
//                            ro.setSpecialId(nto.getSpecial_id());
//                            ro.setRelationId(nto.getRelation_id());
//                            // 获取用户信息
//                            Subscribers sub = subscribersService.selectByPid(users.getId(), ro.getpId());
//                            if (sub == null){
//                                sub = subscribersService.selectBySpecialId(users.getId(), ro.getSpecialId());
//                            }
//                            // 如果存在该用户
//                            if (sub != null) {
//                                // 如果该返利是返购物金 订单付款 充值购物金
//                                boolean flag = shopOrderService.selectByXgt2(sub.getId(), sub.getParentid(), ro.getNumIid()) >= 1;
//                                ShopOrder shopOrder = shopOrderService.selectByXgt(sub.getId(), sub.getParentid(), ro.getNumIid());
//                                if (shopOrder != null && ro.getTkStatus() == 3) {
//                                    if (shopOrderService.updateByXgt(shopOrder.getId()) >= 1) {
//                                        sub.setShopBalance(sub.getShopBalance() + (ro.getPayPrice().multiply(new BigDecimal(0.3))).intValue());
//                                        subscribersService.updateByPrimaryKeySelective(sub);
//                                    }
//                                }
//
//                                if (users.getId().equals("7fdd9bcd5edf4c97a5de0bd0019e4212")){
////                                        sper = userCommission(ratio, users, sub, ro, flag);
////                                        // 推荐者拿去二级比率返利后 剩余的给购买者的比率
////                                        ratio = ratio.multiply(new BigDecimal(1).subtract(sper));
//                                }else {
//                                    ratio = new BigDecimal(usersService.selectByPrimaryKey(users.getId()).getRebateratio()); // 获取一级佣金比例
//                                    if (sub.getIsmember() == 1){
//                                        ratio = new BigDecimal(usersService.selectByPrimaryKey(users.getId()).getRebate2ratio()); // 获取会员一级佣金比例
//                                    }
//                                    // 如果用户存在推荐人
//                                    if (sub.getShareper() != null && !sub.getShareper().isEmpty()) {
//                                        try {
//                                            sper = new BigDecimal(usersService.selectByPrimaryKey(users.getId()).getRebateratio2()); // 获取二级佣金比例
//                                            if (sub.getIsmember() == 1){
//                                                sper = new BigDecimal(usersService.selectByPrimaryKey(users.getId()).getRebate2ratio2()); // 获取会员二级佣金比例
//                                            }
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                        // 增加推荐人的可提现金额
//                                        BigDecimal sSper = sper; // 获取二级比例
//                                        RebateDis rd = new RebateDis(ro.getTradeId(), ro.getNumIid(), ro.getPictUrl(), ro.getItemTitle(), ro.getItemNum(), ro.getPrice(),
//                                                ro.getAlipayTotalPrice(), ro.getCreateTime(), ro.getEarningTime(), ro.getTkStatus(), ro.getOrderType(), ro.getAlipayTotalPrice(),
//                                                !flag ? ro.getIncomeRate().multiply(ro.getCommissionRate()).multiply(ro.getAlipayTotalPrice()).multiply(ratio).multiply(sSper) : new BigDecimal(0),
//                                                flag, sub.getShareper(), sub.getId());
//                                        if (rebateDisService.selectByPrimaryKey(ro.getTradeId()) == null) {
//                                            rebateDisService.insertSelective(rd); // 新增
//                                        } else {
//                                            rebateDisService.updateByPrimaryKeySelective(rd); // 更新
//                                        }
//                                        // 推荐者拿去二级比率返利后 剩余的给购买者的比率
//                                        ratio = ratio.multiply(new BigDecimal(1).subtract(sper));
//                                    }
//                                }
////                                    ro.setUserCommission(!flag ? ro.getIncomeRate().multiply(ro.getCommissionRate()).multiply(ro.getAlipayTotalPrice()).multiply(ratio).multiply(sper) : new BigDecimal(0)); // 分配给用户的佣金
//                                ro.setUserCommission(!flag ? ro.getIncomeRate().multiply(ro.getCommissionRate()).multiply(ro.getAlipayTotalPrice()).multiply(ratio) : new BigDecimal(0)); // 分配给用户的佣金
//                                ro.setUserType(flag); // 用户提现状态
//                            }
//                            if (rebateOrdersService.selectByPrimaryKey(ro.getTradeId()) == null) {
//                                rebateOrdersService.insertSelective(ro); // 新增
//                            } else {
//                                rebateOrdersService.updateByPrimaryKeySelective(ro); // 更新
//                            }
//                        }
//                    } else {
//                        status = false;
//                    }
//                } catch (Exception e) {
//                    System.out.println("暂无数据");
//                }
//            }
//        }
//        System.out.println("查询订单结束");

        return rebateOrdersService.selectAll(pages, fTradeId, fStatus,null,null);
    }
}
